import { createRef, RefObject } from 'react'
import type { Result } from 'ahooks/lib/useRequest/src/types'
import { create } from 'zustand'
import { AgGridReact } from '@ag-grid-community/react'

import { DEFAULT_PAGE_SIZE } from '@/utils/pagination'
import { ISearch, ITemplate, ITemplateRes } from '../interface'

export type TRequest = Result<ITemplateRes, [ISearch]>

export interface IStore {
  gridRef: RefObject<AgGridReact<ITemplate>>
  request?: TRequest
  reqData: ISearch
  setReqData: (val: Partial<ISearch> | ((prevVal: ISearch) => ISearch)) => void
  getData: (partialReqData?: Partial<ISearch> | null) => void
}

export const defaultParams: ISearch = {
  title: '',
  page: 1,
  size: DEFAULT_PAGE_SIZE,
}

export const useBoundStore = create<IStore>((set, get) => {
  return {
    gridRef: createRef(),
    reqData: { ...defaultParams },
    setReqData: val => {
      set(prev => {
        return {
          reqData: {
            ...prev.reqData,
            ...(typeof val === 'function' ? val(prev.reqData) : val),
          },
        }
      })
    },
    getData: partialReqData => {
      const { gridRef, request, reqData } = get()
      request?.run({ ...reqData, ...partialReqData })
      gridRef.current?.api?.ensureIndexVisible(0, 'top')
    },
  }
})
